<?php
/*
 * 用户管理控制器
 * @auth suosuo
 */
 namespace Admin\Controller;

 class AdminController extends CommonController{
// 	添加账户
 	public function add (){
 		if($_POST){
		 	if(!isset($_POST['username']) || !$_POST['username']){
		 		return show(0, '账户名不可为空');
			}
			
			if(!isset($_POST['realname']) || !$_POST['realname']){
		 		return show(0, '昵称不可为空');
			}
			
			if($_POST['admin_id']){
				return $this->save($_POST);
			}
			if(!isset($_POST['password']) || !$_POST['password']){
		 		return show(0, '密码不可为空');
			}
			$data = $_POST;
			$data['password'] = getMd5Password($_POST['password']); 
			$userId = D('Admin')->insert($data);
			if($userId){
				return show(1,"添加用户成功成功");
			}
			
			return show(0,"添加用户失败");
			
	 	}else{
	 		$this->display();
			
	 	}
 	}
 	
// 	编辑
 	public function edit (){
 		$userId = $_GET['id'];
		$user=D("Admin")->find($userId);
		unset($user['password']);
		$this->assign('user',$user);
		$this->display();
 	}
//	保存
	public function save ($data){
		
		$admin_id = $data['admin_id'];
		unset($data['admin_id']);
		unset($data['password']);
		try{
		    $id = D('Admin')->updataById ($admin_id,$data);
			
			if($id===false){
				return show(0, '更新失败');
			}
			return show(1, '更新成功');
		}catch(Exception $e){
			return show(0, $e->message);
		}
		
	}
	
//	删除
	public function del (){
		try{
			if($_POST){
				$id=$_POST['id'];
				$status=$_POST['status'];
				$res=D('Admin')->updataStatusById($id,$status);
				if($res){
					return show(1, '操作成功！');
				}else{
					return show(0, '操作失败！');
				}
			}
		}catch(Exception $e){
			return show(0, $e->getMessage());
		}
		return show(0, '没有提交的数据');
	}
	
	
	
	public function index (){
		/**
		 * 分页操作
		 */
		 $data=array();
		 if(isset($_REQUEST['status']) && in_array($_REQUEST['status'], array(0,1))){
		 	$data['status'] = intval($_REQUEST['status']);
			$this->assign('status',$data['status']);
		 }else{
		 	$this->assign('status',-100);
		 }
		 $adminCount = D("Admin")->getMenusCount($data);
		 
		 $res = new \Think\Page($adminCount,$pageSize);
		 $pageRes = $res->show();
//		 print_r($pageRes);
		 
		$page = $_REQUEST['p'] ? $_REQUEST['p']:1;
		$pageSize = $_REQUEST['pageSize'] ?$_REQUEST['pageSize'] : 5;
 		$admin = D('Admin')->getAdminUserList($data,$page,$pageSize=10);
		$this->assign('pageRes',$pageRes);
		$this->assign('admin',$admin);
//		print_r($admin);
 		$this->display();
	}

	
 }
